package com.fruit.controller.app.user;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import com.fruit.constants.RedisConstant;
import com.fruit.controller.base.BaseController;
import com.fruit.pojo.address.Address;
import com.fruit.pojo.common.Page;
import com.fruit.pojo.user.MyFruitTree;
import com.fruit.pojo.user.UserInfo;
import com.fruit.service.pic.PictureManager;
import com.fruit.service.redis.UserRedisUtil;
import com.fruit.service.rights.UserRightsManager;
import com.fruit.service.user.UserManager;
import com.fruit.util.CookieUtil;
import com.fruit.util.CustomUtil;
import com.fruit.util.MessagesCode;
import com.fruit.util.ResultInfo;
import com.fruit.util.ResultUtil;

/**
 * 用户controller
 * 
 * @author shibeilei
 *
 */
@Controller
@RequestMapping(value = "/app/user/")
public class UserController extends BaseController {


	@Autowired
	private UserManager userService;

	@Autowired
	private PictureManager pictureService;
	
	@Autowired
	private UserRedisUtil userRedisService;
	
	@Autowired
    private UserRightsManager userRightsManager;
	
	@Value("${domain}")
	private String domain;
	
	@Value("${h5_domain}")
	private String h5_domain;
	
	@Value("${top_domain}")
	private String topDomain;
	
	@Value("${app.key}")
	private String key;

	// 用户信息
	@RequestMapping(value = "userCenter", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> userCenter(String userId, HttpServletRequest request) {
		this.logBefore(logger, "用户信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(userId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			UserInfo user = userService.getUser(Integer.parseInt(userId));
			if (user != null) {
				int rightNum= userRightsManager.getRightNum(user.getId());
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				resMap.put("userInfo", user);
				resMap.put("rightNum", rightNum);
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "未找到用户!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 收货地址信息
	@RequestMapping(value = "address/list", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> addressList(String userId, HttpServletRequest request) {
		this.logBefore(logger, "收货地址信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(userId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			List<Address> address = userService.getAddressList(Integer.parseInt(userId));
			if (address.size() > 0) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				resMap.put("address", address);
			} else {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.MESS_ISnULL, "还未设置收货地址!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 添加收货地址
	@RequestMapping(value = "address/save", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> saveAddress(Address address, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "添加收货地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (address == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			} else {
				List<Address> addres = userService.getAddressList(address.getUserId());
				if (addres != null) {
					for (Address addre : addres) {
						if ("01".equals(address.getStatus())) {
							if ("01".equals(addre.getStatus())) {
								addre.setStatus("00");
								userService.updateAddStatus(addre);
							}
						}
					}
				}
				userService.saveAddress(address);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "添加成功!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 修改收货地址
	@RequestMapping(value = "address/update", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateAddress(Address address, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "修改收货地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (address == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			} else {
				if ("01".equals(address.getStatus())) {
					List<Address> addres = userService.getAddressList(address.getUserId());
					if (addres != null) {
						for (Address addre : addres) {
							if ("01".equals(address.getStatus())) {
								if ("01".equals(addre.getStatus())) {
									addre.setStatus("00");
									userService.updateAddStatus(addre);
								}
							}
						}
					}
				}
				userService.updateAddress(address);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 修改收货地址信息
	@RequestMapping(value = "addressMsg", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> addressMsg(String addressId, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "收货地址信息");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(addressId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			Address address = userService.getAddressById(Integer.parseInt(addressId));
			if (address != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "查询成功!"));
				resMap.put("address", address);
			} else {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_ISnULL, "未找到收货地址!"));
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 修改默认地址状态
	@RequestMapping(value = "address/updateStatus", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateStatus(String addressId, String userId, HttpSession session,
			HttpServletRequest request) {
		this.logBefore(logger, "修改默认地址状态");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(addressId) || StringUtils.isEmpty(userId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			List<Address> addres = userService.getAddressList(Integer.parseInt(userId));
			if (addres != null) {
				for (Address addre : addres) {
					if ("01".equals(addre.getStatus())) {
						addre.setStatus("00");
						userService.updateAddStatus(addre);
					}
				}
			}
			Address add = new Address();
			add.setStatus("01");
			add.setId(Integer.parseInt(addressId));
			userService.updateAddStatus(add);
			List<Address> addr = userService.getAddressList(Integer.parseInt(userId));
			if (addr != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "修改成功!"));
				resMap.put("address", addr);
			}
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// 删除收货地址
	@RequestMapping(value = "address/delete", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> deleteAddress(String addressId, HttpSession session, HttpServletRequest request) {
		this.logBefore(logger, "删除收货地址");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(addressId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		try {
			userService.deleteAddress(Integer.parseInt(addressId));
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "删除成功!"));
		} catch (Exception e) {
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// app头像修改
	@RequestMapping(value = "headImage", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> groupImage(String userId, HttpSession session, HttpServletResponse response,
			HttpServletRequest request) {
		this.logBefore(logger, "头像修改");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if (StringUtils.isEmpty(userId)) {
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
			return resMap;
		}
		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
				request.getSession().getServletContext());
		if (multipartResolver.isMultipart(request)) {
			System.out.println("ss");
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile file = multipartRequest.getFile("file");
		InputStream in = null;
		try {
			in = file.getInputStream();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		try {
			UserInfo user = userService.getUser(Integer.parseInt(userId));
			String path = "fruit/user/" +  userId +"/head.png";
			Map imagePath = pictureService.uploadPicture(path, in);
			if(imagePath.size()==0){
				resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败!"));
				return resMap;
			}
			int state=(int)imagePath.get("error");
			if(0==state){
				String imageAddress = (String) imagePath.get("url");
				user.setHeadImage(imageAddress + "?v" + CustomUtil.buildRandom(4));
				userService.updateUserHeadImage(user);
				UserInfo use = userService.getUser(Integer.parseInt(userId));
				if (use != null) {
					resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功!"));
					resMap.put("userInfo", use);
				}
			}else{
				resMap.put("result", this.initResult(ResultInfo.ERROR, "error", "修改失败!"));
				return resMap;
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "系统繁忙!"));
		}
		return resMap;
	}

	// app用户信息修改 昵称 ,性别
	@RequestMapping(value = "userAlter", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> appUpdateUser(String userId, UserInfo user, HttpSession session,
			HttpServletRequest request) {
		this.logBefore(logger, "用户修改");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			if (user == null || StringUtils.isEmpty(userId)) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
				return resMap;
			}
			UserInfo us = userService.getUser(Integer.parseInt(userId));
			if (us == null) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.EXIST, "用户不存在!"));
				return resMap;
			}
			user.setVersion(us.getVersion());
			user.setId(Integer.parseInt(userId));
			userService.updateUserMess(user);
			UserInfo use = userService.getUser(Integer.parseInt(userId));
			if (use != null) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "修改成功"));
				resMap.put("userInfo", use);
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "网络繁忙!"));
		}
		return resMap;
	}

	// 我的果树
	@RequestMapping(value = "farm", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> farm(String userId, Page page) {
		this.logBefore(logger, "我的果树");
		Map<String, Object> resMap = new HashMap<String, Object>();
		Map<String, Object> parame = new HashMap<String, Object>();
		try {
			if (StringUtils.isEmpty(userId)) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.MESS_OUT, "参数不全!"));
				return resMap;
			}
			parame.put("start", (page.getPage() - 1) * page.getShowNum());
			parame.put("number", page.getShowNum());
			parame.put("userId", userId);
			List<MyFruitTree> myTree = userService.getMyFruitTreeList(parame);
			if (myTree == null || myTree.size() == 0) {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.MESS_ISnULL, "您还未购买过商品!"));
			} else {
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "查询成功"));
				resMap.put("MyFruitTree", myTree);
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "网络繁忙!"));
		}
		return resMap;
	}

	@RequestMapping(value = "getUserToken", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getUserToken(HttpServletRequest request, HttpServletResponse response,
			HttpSession session, int loginId) {
		this.logBefore(logger, "获取UserToken");
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			boolean isCreateToken = true;
			String userToken = CookieUtil.getValue(request, "WAP_USER_TOOKEN");
			if(StringUtils.isNotEmpty(userToken)){
				if(userRedisService.isExists(RedisConstant.WAP_USER_TOOKEN+userToken)){
					isCreateToken = false;
					userRedisService.setUserTokenExpire(RedisConstant.WAP_USER_TOOKEN);
				}
			}
			if(isCreateToken){
				UserInfo userInfo = userService.getUserInfoByLoginId(loginId);
				userToken = userRedisService.makeUserToken(userInfo.getId(), key);
				userRedisService.setUserToken(userInfo, userToken);
			}
			CookieUtil.setCookie(response, "WAP_USER_TOOKEN", userToken, 1,"/",topDomain);
			resMap.put("result", this.initResult(ResultInfo.SUCCESS, MessagesCode.SUCCESS, "成功"));
			resMap.put("WAP_USER_TOOKEN", userToken);
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}

	// 修改密码
	@RequestMapping(value = "updateUserPwd", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> updateUserPwd(Page page,HttpServletRequest request) {
		this.logBefore(logger, "修改密码");
		Map<String, Object> resMap = new HashMap<String, Object>();
		String userId=request.getParameter("userId");
		String oldPwd=request.getParameter("oldPwd");
		String newPwd=request.getParameter("newPwd");
		try {
			if (StringUtils.isEmpty(userId)||StringUtils.isEmpty(oldPwd)||StringUtils.isEmpty(newPwd)) {
				resMap.put("result", this.initResult(ResultInfo.ERROR, "no-param", "参数不全!"));
				return resMap;
			}
			resMap=userService.updatePwd(userId,oldPwd,newPwd);
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, "expection", "网络繁忙!"));
		}
		return resMap;
	}
	
	@RequestMapping(value = "getRegister", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> getRegister(HttpServletResponse response, HttpServletRequest request) {
		this.logBefore(logger, "获取注册");
		String userId = request.getParameter("userId");
		Map<String, Object> resMap = new HashMap<String, Object>();
		if(StringUtils.isEmpty(userId)){
			resMap.put("result", this.initResult(ResultInfo.ERROR, "no-param", "参数不全!"));
			return resMap;
		}
		try {
			UserInfo ui=userService.getUser(Integer.parseInt(userId));
			if (ui != null ) {
				String vipcode = ui.getCodePre()+userId+ui.getCodeSuf();
				String href = h5_domain+"/inviteLook?code="+vipcode;
				resMap.put("href", href);
				resMap.put("result", this.initResult(ResultInfo.SUCCESS, "SUCCESS", "成功!"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logError(logger, e.getMessage());
			resMap.put("result", this.initResult(ResultInfo.ERROR, MessagesCode.SYSTEM, "系统繁忙!"));
		}
		this.logAfter(logger);
		return resMap;
	}
	
	@RequestMapping(value = "/aa", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> aa(HttpServletResponse response, HttpServletRequest request) throws Exception {
		Map<String, Object> resMap = new HashMap<String, Object>();
		try {
			resMap=userService.getDownUserNum(123456);
		}catch(Exception e){
			resMap.put("result", ResultUtil.initResult(ResultInfo.ERROR, "exception", "验证失败"));
		}
		return resMap;
	}
}
